package com.leoman.controller.api;

import com.leoman.core.ErrorType;
import com.leoman.core.bean.Result;
import com.leoman.entity.VideoType;
import com.leoman.entity.vo.AppUserGainVo;
import com.leoman.entity.vo.VideoRecordVo;
import com.leoman.exception.*;
import com.leoman.service.AppUserGainService;
import com.leoman.service.VideoService;
import com.leoman.service.VideoTypeService;
import com.leoman.utils.JsonUtil;
import com.leoman.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 视频相关api
 * Created by 涂奕恒 on 2016/10/19 0018.
 */
@Controller
@RequestMapping(value = "api/video")
public class VideoApi {

    @Autowired
    private VideoService videoService;

    @Autowired
    private VideoTypeService videoTypeService;

    @Autowired
    private AppUserGainService appUserGainService;

    /**
     * @api {post} /api/video/type/list 1、视频分类列表
     * @apiVersion 0.0.1
     * @apiName video.typeList
     * @apiGroup video
     *
     * @apiDescription 视频分类列表
     *
     * @apiSuccess {Object}    list
     * @apiSuccess {Integer}   list.id                    分类ID
     * @apiSuccess {String}    list.name                  分类名称
     * @apiSuccess {String}    list.avatar                分类封面
     * @apiSuccess {String}    list.videoNum              包含视频数量
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status":0,
     *      "msg":"",
     *      "data":{
     *          "list": [
     *              {
     *                  "id" : 1,
     *                  "name" : "因特网",
     *                  "avatar" : "http://4.16.3.22:8080/images/cover.jpg",
     *                  "videoNum" : 12
     *              }
     *          ]
     *      }
     * }
     */
    @RequestMapping(value = "/type/list", method = RequestMethod.POST)
    public void typeList(HttpServletResponse response) {
        List<VideoType> list = videoTypeService.iFindList();

        String result = JsonUtil.obj2ApiJson(Result.successListApi(list), "createTime", "updateTime");
        WebUtil.printApi(response, result);
    }

    /**
     * @api {post} /api/video/list 2、视频列表
     * @apiVersion 0.0.1
     * @apiName video.list
     * @apiGroup video
     *
     * @apiDescription 视频列表
     *
     * @apiParam   {Integer}   regionId                   区域Id
     * @apiParam   {Integer}   userId                     用户Id
     * @apiParam   {Integer}   typeId                     分类Id
     * @apiParam   {Integer}   pageNum                    页码
     * @apiParam   {Integer}   pageSize                   每页显示条数
     *
     * @apiSuccess {Object}    list
     * @apiSuccess {Integer}   list.id                    视频ID
     * @apiSuccess {Integer}   list.sendType              投放形式，1=一般形式，2=红包形式，3=其他形式，4=免费形式
     * @apiSuccess {Integer}   list.typeId                视频分类ID
     * @apiSuccess {String}    list.typeName              视频分类名称
     * @apiSuccess {Integer}   list.name                  视频名称
     * @apiSuccess {String}    list.cover                 封面图
     * @apiSuccess {String}    list.url                   视频链接
     * @apiSuccess {String}    list.duration              时长
     * @apiSuccess {String}    list.synopsis              简介
     * @apiSuccess {Integer}   list.playNum               播放量
     * @apiSuccess {Integer}   list.praiseNum             点赞数
     * @apiSuccess {Integer}   list.treadNum              踩数
     * @apiSuccess {Object}    list.regionNames           投放区域名称，中间用英文逗号隔开
     * @apiSuccess {String}    list.startTime             开始时间
     * @apiSuccess {String}    list.endTime               结束时间
     * @apiSuccess {Integer}   list.price                 投放单价
     * @apiSuccess {Integer}   list.count                 投放次数
     * @apiSuccess {Integer}   list.isSend                是否允许投递简历（0：否，1：是）
     * @apiSuccess {Integer}   list.isGet                 是否领取奖励（0：否，1：是）
     * @apiSuccess {Integer}   list.isPraise              是否点赞（0：否，1：是）
     * @apiSuccess {Integer}   list.isTread               是否踩（0：否，1：是）
     * @apiSuccess {String}    list.createTime            创建时间
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status":0,
     *      "msg":"",
     *      "data":{
     *          "page": {
     *              "totalNum": 0,
     *              "totalPage": 0,
     *              "currentPage": 1
     *          },
     *          "list": [
     *              {
     *                  "id" : 1,
     *                  "sendType" : 1,
     *                  "typeId" : 1,
     *                  "typeName" : "因特网",
     *                  "name" : "测试视频001",
     *                  "cover" : "http://4.16.3.22:8080/images/cover.jpg",
     *                  "url" : "http://www.qq.com",
     *                  "duration" : "4分32秒",
     *                  "synopsis" : "我的视频简介",
     *                  "playNum" : 245,
     *                  "praiseNum" : 666,
     *                  "treadNum" : 124,
     *                  "regionNames" : "东城区,海淀区,崇文区",
     *                  "startTime" : "1476843473471",
     *                  "endTime" : "1476843473472",
     *                  "price" : 3,
     *                  "count" : 1000,
     *                  "isSend" : 0,
     *                  "isGet" : 0,
     *                  "isPraise" : 1,
     *                  "isTread" : 0,
     *                  "createTime" : "1476843673494"
     *              }
     *          ]
     *      }
     * }
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public void list(HttpServletResponse response, Integer regionId, Integer userId, Integer typeId, Integer pageNum, Integer pageSize) {
        try {
            Page<VideoRecordVo> page = videoService.iPageForApp(regionId, userId, typeId, pageNum, pageSize);
            Map<String, Object> dataMap = JsonUtil.fitting(page);
            String result = JsonUtil.obj2ApiJson(Result.successApi(dataMap), "tempStatus", "tempContent");
            WebUtil.printApi(response, result);
        } catch (ParamErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_NOT_PARAM));
        } catch (UserNotFindException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_USER_NOT_FIND));
        } catch (UserSealStatusException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_USER_STATUS_DISABLED));
        }
    }

    /**
     * @api {post} /api/video/info 3、视频详情
     * @apiVersion 0.0.1
     * @apiName video.info
     * @apiGroup video
     *
     * @apiDescription 视频详情
     *
     * @apiParam   {Integer}   videoId                         视频Id     （必填）
     * @apiParam   {Integer}   userId                          用户Id
     *
     * @apiSuccess {Object}    videoInfo
     * @apiSuccess {Integer}   videoInfo.id                    视频ID
     * @apiSuccess {Integer}   videoInfo.sendType              投放形式，1=一般形式，2=红包形式，3=其他形式，4=免费形式
     * @apiSuccess {Integer}   videoInfo.typeId                视频分类ID
     * @apiSuccess {String}    videoInfo.typeName              视频分类名称
     * @apiSuccess {Integer}   videoInfo.name                  视频名称
     * @apiSuccess {String}    videoInfo.cover                 封面图
     * @apiSuccess {String}    videoInfo.url                   视频链接
     * @apiSuccess {String}    videoInfo.duration              时长
     * @apiSuccess {String}    videoInfo.synopsis              简介
     * @apiSuccess {Integer}   videoInfo.playNum               播放量
     * @apiSuccess {Integer}   videoInfo.praiseNum             点赞数
     * @apiSuccess {Integer}   videoInfo.treadNum              踩数
     * @apiSuccess {Object}    videoInfo.regionNames           投放区域名称，中间用英文逗号隔开
     * @apiSuccess {String}    videoInfo.startTime             开始时间
     * @apiSuccess {String}    videoInfo.endTime               结束时间
     * @apiSuccess {Integer}   videoInfo.price                 投放单价
     * @apiSuccess {Integer}   videoInfo.count                 投放次数
     * @apiSuccess {Integer}   videoInfo.isSend                是否允许投递简历（0：否，1：是）
     * @apiSuccess {Integer}   videoInfo.isGet                 是否领取奖励（0：否，1：是）
     * @apiSuccess {Integer}   videoInfo.isPraise              是否点赞（0：否，1：是）
     * @apiSuccess {Integer}   videoInfo.isTread               是否踩（0：否，1：是）
     * @apiSuccess {String}    videoInfo.createTime            创建时间
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status":0,
     *      "msg":"",
     *      "data":{
     *          "videoInfo": [
     *              {
     *                  "id" : 1,
     *                  "sendType" : 1,
     *                  "typeId" : 1,
     *                  "typeName" : "因特网",
     *                  "name" : "测试视频001",
     *                  "cover" : "http://4.16.3.22:8080/images/cover.jpg",
     *                  "url" : "http://www.qq.com",
     *                  "duration" : "4分32秒",
     *                  "synopsis" : "我的视频简介",
     *                  "playNum" : 245,
     *                  "praiseNum" : 666,
     *                  "treadNum" : 124,
     *                  "regionNames" : "东城区,海淀区,崇文区",
     *                  "startTime" : "1476843473471",
     *                  "endTime" : "1476843473472",
     *                  "price" : 3,
     *                  "count" : 1000,
     *                  "isSend" : 0,
     *                  "isGet" : 0,
     *                  "isPraise" : 1,
     *                  "isTread" : 0,
     *                  "createTime" : "1476843673494"
     *              }
     *          ]
     *      }
     * }
     */
    @RequestMapping(value = "/info", method = RequestMethod.POST)
    public void info(HttpServletResponse response, Integer videoId, Integer userId) {
        try {
            VideoRecordVo videoRecordVo = videoService.iFindOneForApp(videoId, userId);
            String result = JsonUtil.obj2ApiJson(Result.successInfoApi(videoRecordVo, "videoInfo"), "tempStatus", "tempContent");
            WebUtil.printApi(response, result);
        } catch (ParamErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_NOT_PARAM));
        } catch (VideoNotFindException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_VIDEO_NOT_FIND));
        } catch (UserNotFindException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_USER_NOT_FIND));
        } catch (UserSealStatusException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_USER_STATUS_DISABLED));
        }
    }

    /**
     * @api {post} /api/video/praise 4、点赞 or 踩
     * @apiVersion 0.0.1
     * @apiName video.praise
     * @apiGroup video
     *
     * @apiDescription 点赞 or 踩
     *
     * @apiParam {Integer}   userId           用户ID                           (必填)
     * @apiParam {Integer}   videoId          视频ID                           (必填)
     * @apiParam {Integer}   type             类型 1=点赞 2=踩，不填默认为点赞
     * @apiParam {Integer}   flag             操作 1=点赞 or 踩 2=取消点赞 or 取消踩，不填默认为点赞 or 踩
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status": 0,
     *      "msg": "",
     *      "data": {}
     * }
     */
    @RequestMapping(value = "/praise", method = RequestMethod.POST)
    public void praise(HttpServletResponse response, Integer userId, Integer videoId, Integer type, Integer flag) {
        try {
            videoService.iPraiseVideo(userId, videoId, type, flag);
            WebUtil.printApi(response, JsonUtil.obj2ApiJson(Result.successApi()));
        } catch (ParamErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_NOT_PARAM));
        } catch (UserNotFindException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_USER_NOT_FIND));
        } catch (VideoNotFindException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_VIDEO_NOT_FIND));
        } catch (PraiseNotFindException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_PRAISE_NOT_FIND));
        } catch (PraiseExistException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_PRAISE_EXIST));
        } catch (TreadNotFindException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_TREAD_NOT_FIND));
        } catch (TreadExistException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_TREAD_EXIST));
        } catch (UserSealStatusException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_USER_STATUS_DISABLED));
        }
    }

    /**
     * @api {post} /api/video/gain 5、看视频获取奖励
     * @apiVersion 0.0.1
     * @apiName video.gain
     * @apiGroup video
     *
     * @apiDescription 看视频获取奖励
     *
     * @apiParam {Integer}   userId           用户ID                           (必填)
     * @apiParam {Integer}   videoId          视频ID                           (必填)
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status": 0,
     *      "msg": "",
     *      "data": {}
     * }
     */
    @RequestMapping(value = "/gain", method = RequestMethod.POST)
    public void gain(HttpServletResponse response, Integer userId, Integer videoId) {
        try {
            videoService.iGainVideo(userId, videoId);
            WebUtil.printApi(response, JsonUtil.obj2ApiJson(Result.successApi()));
        } catch (ParamErrorException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_NOT_PARAM));
        } catch (UserNotFindException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_USER_NOT_FIND));
        } catch (VideoNotFindException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_VIDEO_NOT_FIND));
        } catch (GainExistException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_GAIN_EXIST));
        } catch (GainNotFindException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_GAIN_NOT_FIND));
        } catch (UserSealStatusException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_USER_STATUS_DISABLED));
        } catch (GainCountMaxException e) {
            WebUtil.printApi(response, Result.failureApi(ErrorType.ERROR_GAIN_COUNT_MAX));
        }
    }

    /**
     * @api {post} /api/video/gain/list 6、收益排行列表
     * @apiVersion 0.0.1
     * @apiName video.gainList
     * @apiGroup video
     *
     * @apiDescription 收益排行列表
     *
     * @apiParam   {Integer}   index                      排行数量，不传默认取前七名
     *
     * @apiSuccess {Object}    list
     * @apiSuccess {Integer}   list.id                    用户ID
     * @apiSuccess {String}    list.nickName              用户昵称
     * @apiSuccess {String}    list.avatar                用户头像
     * @apiSuccess {Integer}   list.money                 用户总收益
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status":0,
     *      "msg":"",
     *      "data":{
     *          "list": [
     *              {
     *                  "id" : 1,
     *                  "nickName" : "张雨生",
     *                  "avatar" : "http://4.16.3.22:8080/images/cover.jpg",
     *                  "money" : 421
     *              }
     *          ]
     *      }
     * }
     */
    @RequestMapping(value = "/gain/list", method = RequestMethod.POST)
    public void gainList(HttpServletResponse response, Integer index) {
        List<AppUserGainVo> list = appUserGainService.iFindListRankInfoByIndex(index);
        String result = JsonUtil.obj2ApiJson(Result.successListApi(list));
        WebUtil.printApi(response, result);
    }

    /**
     * @api {post} /api/video/gain/newList 7、用户最新收益列表
     * @apiVersion 0.0.1
     * @apiName video.newGainList
     * @apiGroup video
     *
     * @apiDescription 用户最新收益列表
     *
     * @apiParam   {Integer}   index                      数量，不传默认取最新七条（跟排名一样）
     *
     * @apiSuccess {Object}    list
     * @apiSuccess {Integer}   list.id                    用户ID
     * @apiSuccess {String}    list.nickName              用户昵称
     * @apiSuccess {Integer}   list.money                 用户收益
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "status":0,
     *      "msg":"",
     *      "data":{
     *          "list": [
     *              {
     *                  "id" : 1,
     *                  "nickName" : "张雨生",
     *                  "money" : 4
     *              }
     *          ]
     *      }
     * }
     */
    @RequestMapping(value = "/gain/newList", method = RequestMethod.POST)
    public void newGainList(HttpServletResponse response, Integer index) {
        List<AppUserGainVo> list = appUserGainService.iFindListDynamicByIndex(index);
        String result = JsonUtil.obj2ApiJson(Result.successListApi(list), "avatar");
        WebUtil.printApi(response, result);
    }
}
